package com.tywj.lib.storage.mmkv

import android.content.Context
import com.tencent.mmkv.MMKV

/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/5/8
 *     desc   : MMKV缓存框架
 *     version: 1.0.0
 * </pre>
 */
class MMKVStorage(
    // 唯一id，用来区分不同的存储map
    id: String,
    // 加密key
    cryptKey: String? = null,
    // 是否为单进程
    isSingleProcess: Boolean = true
) : IStorage {

    private val kv: MMKV =
        MMKV.mmkvWithID(id, if (isSingleProcess) MMKV.SINGLE_PROCESS_MODE else MMKV.MULTI_PROCESS_MODE, cryptKey)

    companion object {
        /**
         * 初始化MMKV缓存框架
         * @return 缓存路径根目录
         */
        fun initialize(context: Context): String {
            return MMKV.initialize(context)
        }
    }

    override fun put(key: String, value: Boolean): Boolean = kv.encode(key, value)

    override fun put(key: String, value: ByteArray): Boolean = kv.encode(key, value)

    override fun put(key: String, value: Double): Boolean = kv.encode(key, value)

    override fun put(key: String, value: Float): Boolean = kv.encode(key, value)

    override fun put(key: String, value: Int): Boolean = kv.encode(key, value)

    override fun put(key: String, value: Long): Boolean = kv.encode(key, value)

    override fun put(key: String, value: Set<String>): Boolean = kv.encode(key, value)

    override fun put(key: String, value: String): Boolean = kv.encode(key, value)

    override fun getBoolean(key: String, defValue: Boolean): Boolean = kv.getBoolean(key, defValue)

    override fun getByteArray(key: String): ByteArray = kv.decodeBytes(key)

    override fun getDouble(key: String, defValue: Double): Double = kv.decodeDouble(key, defValue)

    override fun getFloat(key: String, defValue: Float): Float = kv.decodeFloat(key, defValue)

    override fun getInt(key: String, defValue: Int): Int = kv.decodeInt(key, defValue)

    override fun getLong(key: String, defValue: Long): Long = kv.decodeLong(key, defValue)

    override fun getStringSet(key: String): Set<String>? = kv.decodeStringSet(key)

    override fun getString(key: String): String? = kv.decodeString(key)

    override fun remove(key: String) {
        kv.remove(key)
    }

    override fun clear() {
        kv.clear()
    }

    override fun contains(key: String): Boolean = kv.contains(key)

    override fun allKeys(): Array<String> = kv.allKeys()
}